#include "stdafx.h"
#include "IDT.h"

extern "C"
{
	IDT* pIdt = NULL;

	extern void set_debug_traps();

	#define PORT 0x3f8   /* COM1 */
 
	void init_serial() 
	{
	   outb(PORT + 1, 0x00);    // Disable all interrupts
	   outb(PORT + 3, 0x80);    // Enable DLAB (set baud rate divisor)
	   outb(PORT + 0, 0x03);    // Set divisor to 3 (lo byte) 38400 baud
	   outb(PORT + 1, 0x00);    //                  (hi byte)
	   outb(PORT + 3, 0x03);    // 8 bits, no parity, one stop bit
	   outb(PORT + 2, 0xC7);    // Enable FIFO, clear them, with 14-byte threshold
	   outb(PORT + 4, 0x0B);    // IRQs enabled, RTS/DSR set
	}

	void InitGDB(IDT* idt)
	{
		pIdt = idt;

		set_debug_traps();

		init_serial();
	}

	int is_transmit_empty() 
	{
		return inb(PORT + 5) & 0x20;
	}

	/* write a single character      */
	void putDebugChar(char ch)
	{
		while (is_transmit_empty() == 0);
 
		outb(PORT, ch);
	}

	int serial_received() 
	{
		return inb(PORT + 5) & 1;
	}

	/* read and return a single char */
	int getDebugChar()
	{
		while (serial_received() == 0);
 
		return inb(PORT);
	}

	/* assign an exception handler   */
	void exceptionHandler(int exceptionID, void (*handler)())
	{
		pIdt->SetSys32ISRHandler(exceptionID, handler);
	}

}
